package icloud.com.myapplication.ui.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import icloud.com.myapplication.MyApplication;
import icloud.com.myapplication.dao.User;
import icloud.com.myapplication.db.DaoSession;
import icloud.com.myapplication.db.UserDao;
import icloud.com.myapplication.ui.fragment.SecondFragment;
import icloud.com.myapplication.utils.Config;
import icloud.com.myapplication.utils.DiskLruCache;
import icloud.com.myapplication.R;


public class SecondActivity extends AppCompatActivity implements SecondFragment.OnFragmentInteractionListener {

    private static final String TAG = "Activity";

    LruCache<String, Bitmap> mLruCache;

    DiskLruCache mDiskLruCache;
    
    @BindView(R.id.et)
    EditText mEditText;

    @BindView(R.id.btn)
    Button  mButton;
    
    @BindView(R.id.imageview)
    ImageView imageView;

    UserDao userDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        ButterKnife.bind(this);
        //
        log("onCreate");
        //申请获取联系人权限
//        mButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (ContextCompat.checkSelfPermission(SecondActivity.this,
//                        Manifest.permission.READ_CONTACTS)
//                        != PackageManager.PERMISSION_GRANTED) {
//
//                    // Should we show an explanation?
//                    if (ActivityCompat.shouldShowRequestPermissionRationale(SecondActivity.this,
//                            Manifest.permission.READ_CONTACTS)) {
//                        Toast.makeText(SecondActivity.this, "上次已经拒绝", Toast.LENGTH_SHORT).show();
//                        // Show an expanation to the user *asynchronously* -- don't block
//                        // this thread waiting for the user's response! After the user
//                        // sees the explanation, try again to request the permission.
//
//                    } else {
//
//                        // No explanation needed, we can request the permission.
//
//                        ActivityCompat.requestPermissions(SecondActivity.this,
//                                new String[]{Manifest.permission.READ_CONTACTS},
//                                MY_PERMISSIONS_REQUEST_READ_CONTACTS);
//
//                        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
//                        // app-defined int constant. The callback method gets the
//                        // result of the request.
//                    }
//                } else {
//                    Toast.makeText(SecondActivity.this, "Permission Denied", Toast.LENGTH_SHORT)
//                            .show();
//                }
//            }
//        });
//        mEditText=(EditText)findViewById(R.id.et);
//        mEditText.setFilters(new InputFilter[]{new EmojiFilter()});
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                Toast.makeText(SecondActivity.this,mEditText.getText().toString(),Toast.LENGTH_LONG)
//                        .show();
                Log.v("TAG",mEditText.getText().toString());
            }
        });
        setEmojiToTextView();
        //
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        SecondFragment secondFragment=new SecondFragment();
        transaction.replace(R.id.fragment_container, secondFragment);
        transaction.commitNow();
//        setResult(2000);
//        finish();
        //测试GreenDao
        DaoSession daoSession = MyApplication.getInstance().getDaoSession();
        userDao = daoSession.getUserDao();
        User user = new User();
        user.setId(1);
        user.setName("小明");
        user.setAge(16);
//        userDao.insert(user);
        //插入或者替换
        userDao.insertOrReplace(user);
        //加载图片
        Glide.with(this).load("https://t12.baidu.com/it/u=36328106,1065212583&fm=173&app=12&f=JPG?w=493&h=279&s=3BF1138E0C560ED47C703E930300F08D").into(imageView);
    }
    /**************************greendao相关 ***************************/
    public void delete(User user){
        userDao.delete(user);
    }

    public void deleteByUserId(long userid){
        userDao.deleteByKey(1L);
    }

    public void update(User user){
        userDao.update(user);
    }

    public List query(){
        return userDao.loadAll();// 查询所有记录
    }

    public User query2(){
        return userDao.loadByRowId(1);//根据ID查询
    }

    /**************************greendao相关 ***************************/

    //查询年龄大于10的用户
    public List query4(){
        QueryBuilder builder = userDao.queryBuilder();
        return  builder.where(UserDao.Properties.Age.gt(10)).build().list();
    }

    @OnClick(R.id.btn)
    public void onButtonClick(View view) {
        Toast.makeText(this, "Button被点击了", Toast.LENGTH_SHORT).show();
    }

    private void setEmojiToTextView(){
        int unicodeJoy = 0x1F602;
        String emojiString = getEmojiStringByUnicode(unicodeJoy);
        mEditText.setText(emojiString);
        Toast.makeText(this,mEditText.getText().toString(),Toast.LENGTH_LONG).show();
    }

    private String getEmojiStringByUnicode(int unicode){
        return new String(Character.toChars(unicode));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case Config.MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(SecondActivity.this, "获取联系人权限成功", Toast.LENGTH_SHORT)
                            .show();
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    Toast.makeText(SecondActivity.this, "获取联系人权限失败", Toast.LENGTH_SHORT)
                            .show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        log("onResume");
    }

    @Override
    protected void onStart() {
        super.onStart();
        log("onStart");
    }

    @Override
    protected void onPause() {
        super.onPause();
        log("onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        log("onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        log("onDestroy");
    }

    private void log(String methodName) {
        Log.d(TAG, SecondActivity.class.getSimpleName() + "---" + methodName + "--");
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
        
    }
}
